#!/usr/bin/env python3

# strict_pam - manipulating PAM configuration in a strict manner
#
# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


from ._main import PamGroup


class Fc:

    @staticmethod
    def getPamGroup(data, pamGroup, filterFunc=None):
        ruleList = data.get(pamGroup, [])
        if filterFunc is not None:
            ruleList2 = []
            ruleIndexList = []
            for i, line in enumerate(ruleList):
                if filterFunc(line):
                    ruleList2.append(line)
                    ruleIndexList.append(i)
            return (ruleList2, ruleIndexList)
        else:
            return (ruleList, range(0, len(ruleList)))

    @staticmethod
    def putPamGroup(data, pamGroup):
        if pamGroup not in data:
            data[pamGroup] = []
        return data[pamGroup]

    @staticmethod
    def filterRuleList(ruleList, modulePath):
        ret = []
        for rule in ruleList:
            if rule.module_path == modulePath:
                ret.append(rule)
        return ret

    @staticmethod
    def ruleListHasModule(ruleList, modulePath):
        for rule in ruleList:
            if rule.module_path == modulePath:
                return True
        return False

    @staticmethod
    def ruleListRemoveModule(ruleList, modulePath):
        for i in reversed(range(0, len(ruleList))):
            if ruleList[i].module_path == modulePath:
                ruleList.pop(i)

    @classmethod
    def groupsHasModule(cls, data, pamGroupInfo, modulePath):
        pamGroups, includeOrExclude = cls._parseGroupInfo(pamGroupInfo)

        for pamGroup, ruleList in data.items():
            if includeOrExclude:
                if pamGroup in pamGroups and Fc.ruleListHasModule(ruleList, modulePath):
                    return True
            else:
                if pamGroup not in pamGroups and Fc.ruleListHasModule(ruleList, modulePath):
                    return True
        return False

    @classmethod
    def groupsRemoveModule(cls, data, pamGroupInfo, modulePath):
        pamGroups, includeOrExclude = cls._parseGroupInfo(pamGroupInfo)

        for pamGroup, ruleList in data.items():
            if includeOrExclude:
                if pamGroup in pamGroups:
                    cls.ruleListRemoveModule(ruleList, modulePath)
            else:
                if pamGroup not in pamGroups:
                    cls.ruleListRemoveModule(ruleList, modulePath)

    @staticmethod
    def _parseGroupInfo(pamGroupInfo):
        if isinstance(pamGroupInfo, PamGroup):
            pamGroups = [pamGroupInfo]
            includeOrExclude = True
        elif pamGroupInfo == "*":
            pamGroups = []
            includeOrExclude = False
        else:
            if isinstance(pamGroupInfo[-1], PamGroup):
                pamGroups = pamGroupInfo
                includeOrExclude = True
            elif isinstance(pamGroupInfo[-1], bool):
                pamGroups = pamGroupInfo[:-1]
                includeOrExclude = pamGroupInfo[-1]
        return (pamGroups, includeOrExclude)

    @staticmethod
    def isAfterInGroupIfExist(pamService, featureObj, featureCls):
        featureObjBefore = pamService.get_feature(featureCls)
        if featureObjBefore is not None:
            return featureObjBefore.get_rule_index() < featureObj.get_rule_index()
        else:
            return True

    @staticmethod
    def changeAfterIndexIfExist(pamService, featureCls, curIndex):
        featureObjBefore = pamService.get_feature(featureCls)
        if featureObjBefore is not None:
            return max(curIndex, featureObjBefore.get_rule_index())
        else:
            return curIndex

    @staticmethod
    def moduleArgumentsEquals(module_arguments, target):
        module_arguments = module_arguments.split(" ")
        if isinstance(target, list):
            if module_arguments != target:
                return False
        elif isinstance(target, set):
            if len(module_arguments) != len(target) or set(module_arguments) != target:
                return False
        else:
            assert False
        return True

    @staticmethod
    def moduleArgumentsContains(module_arguments, target):
        module_arguments = module_arguments.split(" ")
        for x in target:
            if x in module_arguments:
                return True
        return False
